
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace 正则表达式
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string id = textBox1.Text;
            string result = Parseid(id);
            MessageBox.Show(result);
        }
        static string Parseid(string id)
        {
            string pattern = @"^\d{17}(?:\d|X)$";
            string birth = "";
            if (id.Length == 18)
            { birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-"); }
            if (id.Length != 18)
            {
                return "身份证长度不正确!";
            }
            DateTime time = new DateTime();

            int[] arr_weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };     // 加权数组
            string[] id_last = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" };   // 校验数组
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum += arr_weight[i] * int.Parse(id[i].ToString());
            }
            int result = sum % 11;// 实际校验位的值
            bool a, b, c;
            a = Regex.IsMatch(id, pattern);
            b = id_last[result] == id[17].ToString();
            c = DateTime.TryParse(birth, out time);

            if(a&&b&&c)
            {
                return "身份证格式正确！";
            }
            else if (a&&!b)
            {
                if (c)
                {
                    return "最后一位校验错误！";
                }
                else
                {
                    return "最后一位校验错误！且日期错误！";
                }
            }
            else if (a&&!c)
            {
                if (b)
                {
                    return "身份证日期错误且校验码错误！";
                }
                else
                {
                    return "身份证日期错误但校验码正确！";
                }
            }
            else if(!a)
            {
                return "身份证格式错误！";
            }
            return "";
        }
    }
    
}